import React from 'react';
import DocumentTitle from 'react-document-title';
import Icon from '@components/icon';
import ImageView from '@components/image-view';
import {fetch} from '@utils/Fetch';
import {Toast} from 'antd-mobile';
import './preview.less';

class Preview extends React.PureComponent {
  state = {
    visible: false
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.visible !== nextProps.visible
      && nextProps.visible !== this.state.visible) {
      this.setState({visible: nextProps.visible});
    }
  }

  fDelete = async (e) => {
    e.stopPropagation();
    const _id = this.props._id;
    if (!_id) {
      return;
    }
    fetch(`/api/material?_id=${_id}`).delete()
      .success(res => {
        res.message && Toast.success(res.message);
        this.fClose();
      });
  };
  fClose = (e) => {
    e && e.stopPropagation();
    this.setState({visible: false});
    const {onClose} = this.props;
    if (typeof onClose === 'function') {
      onClose();
    }
  };

  render() {
    const {url, _id, regionText, isLazy} = this.props;
    return (
      <DocumentTitle title='预览'>
        <div className='pl-preview'>
          <ImageView className='pl-preview-image'
                     src={url}
                     onClick={this.fClose}
                     isLazy={isLazy}
          />
          <div className='pl-preview-footer'>
            {regionText || '其他'}
            {
              !_id ? null : (
                <div onClick={this.fDelete} className='pl-preview-delete'>
                  <Icon type='delete' style={{color: '#ff4d4f'}} />
                </div>
              )
            }
          </div>
        </div>
      </DocumentTitle>
    )
  }
}

export default Preview;
Preview.defaultProps = {
  isLazy: true
};
